const crypto = require('crypto');
const characters = '0123456789abcdefghijklmnopqrstuvwxyz';

export class Password {
	static getRandomCharacter(): string {
		return characters[Math.floor(characters.length * Math.random())];
	}

	static getSalt(length: number = 8): string {
		let out = '';
		for (let i = 0; i < length; i++) {
			out += this.getRandomCharacter();
		}
		return out;
	}

	static getHashedPassword(plainText: string, saltLength: number = 8): string {
		let salt = this.getSalt(saltLength);
		let hash = crypto.createHash('sha256');
		hash.update(plainText);
		hash.update(salt);
		let out = hash.digest('hex').toString();
		return `1|${out}|${salt}`;
	}

	static verify(plainText: string, hash: string): boolean {
		let hashParts = hash.split('|');
		if (hashParts.length !== 3) {
			return false;
		}
		if (hashParts[0] === '1') {
			let glob = hashParts[1];
			let salt = hashParts[2];
			let sha256 = crypto.createHash('sha256');
			sha256.update(plainText);
			sha256.update(salt);
			return glob === sha256.digest('hex').toString();
		} else {
			// unsupported hash mode
			return false;
		}
	}
}
